<?php

namespace plugin\ycMassage\app\api\controller;

use app\common\manager\SettingsMgr;
use Endroid\QrCode\Builder\Builder;
use Endroid\QrCode\Encoding\Encoding;
use Endroid\QrCode\ErrorCorrectionLevel\ErrorCorrectionLevelHigh;
use Endroid\QrCode\RoundBlockSizeMode\RoundBlockSizeModeMargin;
use Endroid\QrCode\Writer\PngWriter;
use GuzzleHttp\Client;
use plugin\ycMassage\app\BaseController;
use plugin\ycMassage\app\model\MassageUserChannels;
use plugin\ycMassage\app\model\MassageUserChannelsStatistics;
use plugin\ycMassage\app\validate\MassageUserChannels as ValidateMassageUserChannels;
use plugin\ycMassage\utils\enum\Examine;
use plugin\ycMassage\utils\enum\NoticeType;
use plugin\ycMassage\utils\enum\State;
use plugin\ycMassage\utils\notice\Notice;
use plugin\ycMassage\utils\WechatHelper;
use support\Request;
use think\facade\Db;
use think\facade\Env;

class ChannelsController extends BaseController
{
    public function getAddress(Request $request)
    {
        $channels_id = $request->channels_id;
        $model = MassageUserChannels::where(['id' => $channels_id, 'saas_appid' => $request->saas_appid])->find();
        if ($model) {
            $data=[
                'province_id'=>$model->province_id,
                'province'=>$model->province,
                'city_id'=>$model->city_id,
                'city'=>$model->city,
                'area_id'=>$model->area_id,
                'area'=>$model->area,
                'street_id'=>$model->street_id,
                'street'=>$model->street,
                'address_detail'=>$model->address_detail,
                'name'=>'',
                'mobile'=>'',
                'is_default'=>0,
                'latitude'=>$model->latitude,
                'longitude'=>$model->longitude,
            ];
            return $this->successRes($data);
        }
        return $this->fail('未找到渠道商信息');
    }
    public function info(Request $request)
    {
        $model = MassageUserChannels::alias('a')->where(['a.uid' => $request->uid, 'a.saas_appid' => $request->saas_appid])
            ->whereIn('a.examine', [
                Examine::WAIT['value'],
                Examine::NO['value'],
            ])->order('a.id desc')
            ->join('massage_user_channels_category b', 'a.category_id = b.id', 'LEFT')
            ->field('a.*,b.title as category')
            ->find();
        if ($model) {
            return $this->successRes($model);
        }
        return $this->fail('未找到渠道商申请信息');
    }
    public function apply(Request $request)
    {
        $D = $request->post();
        $uid = $request->uid;
        $saas_appid = $request->saas_appid;
        $validate = new ValidateMassageUserChannels;
        if (!$validate->check($D)) {
            return $this->fail($validate->getError());
        }
        Db::startTrans();
        try {
            if (empty($D['id'])) {
                $model = new MassageUserChannels;
            } else {
                $model = MassageUserChannels::where(['id' => $D['id']])->find();
                if (!$model) {
                    throw new \Exception('未找到渠道商申请信息');
                }
                if($model->uid&&$model->uid!=$uid){
                    throw new \Exception('无权限操作');
                }
            }
            $model->uid = $uid;
            $model->saas_appid = $saas_appid;
            $model->mobile = $D['mobile'];
            $model->title = $D['title'];
            $model->category_id = (int)$D['category_id'];
            $model->province_id = (int)$D['province_id'];
            $model->province = $D['province'];
            $model->city_id = (int)$D['city_id'];
            $model->city = $D['city'];
            $model->area_id = (int)$D['area_id'];
            $model->area = $D['area'];
            $model->street_id = (int)$D['street_id'];
            $model->street = $D['street'];
            $model->address_detail = $D['address_detail'];
            $model->latitude = $D['latitude'];
            $model->longitude = $D['longitude'];
            $model->examine = Examine::WAIT['value'];
            $model->state = State::NO['value'];
            $model->remark = $D['remark'];
            $model->save();
            $notice = new Notice();
            $notice->saas_appid = $model->saas_appid;
            $notice->role = ['ADMIN'];
            $notice->type = NoticeType::WORK_ORDER['value'];
            $notice->setData([
                'service_name' => '渠道商申请审核',
                'name' => $model->title,
                'time' => date('Y-m-d H:i:s'),
            ]);
            $notice->send();
            Db::commit();
        } catch (\Throwable $th) {
            Db::rollback();
            return $this->fail($th->getMessage());
        }
        return $this->success('申请成功,请等待审核');
    }
    public function user(Request $request)
    {
        $model = MassageUserChannels::alias('a')->where(['a.uid' => $request->uid, 'a.saas_appid' => $request->saas_appid])
            ->join('massage_user_channels_category b', 'a.category_id = b.id', 'LEFT')
            ->field('a.*,b.title as category')
            ->order('a.state desc,a.id asc')->select();
        if (!$model->isEmpty()) {
            $model->each(function ($item) {
                $item->title = "{$item->title} - {$item->category}";
            });
            return $this->successRes($model);
        }
        return $this->fail('未找到渠道商申请信息');
    }
    public function statistics(Request $request)
    {
        $channels_id = $request->get('channels_id');
        $date = $request->get('date');
        $uid = $request->uid;
        $saas_appid = $request->saas_appid;
        $model = MassageUserChannelsStatistics::where(['uid' => $uid, 'channels_id' => $channels_id, 'saas_appid' => $saas_appid]);
        switch ($date) {
            case 'yesterday':
                $model->whereDay('create_time', 'yesterday');
                break;
            case 'week':
                $model->whereWeek('create_time');
                break;
            case 'month':
                $model->whereMonth('create_time');
                break;
            case 'last_month':
                $model->whereMonth('create_time', 'last month');
                break;
            default:
                $model->whereDay('create_time');
                break;
        }
        $MassageUserChannelsStatistics = $model->select();
        $data = [
            'order_num' => 0,
            'order_price' => 0,
            'duration' => 0,
            'new_customers' => 0,
            'commission' => 0,
            'browse_num' => 0,
        ];
        foreach ($MassageUserChannelsStatistics as $item) {
            $data['order_num'] += $item->order_num;
            $data['order_price'] += $item->order_price;
            $data['duration'] += $item->duration;
            $data['new_customers'] += $item->new_customers;
            $data['commission'] += $item->commission;
            // $data['browse_num'] += $item->browse_num;
        }
        return $this->successRes($data);
    }
    public function createQrcode(Request $request)
    {
        $channels_id = $request->post('channels_id');
        $uid = $request->uid;
        $saas_appid = $request->saas_appid;
        $model = MassageUserChannels::where(['id' => $channels_id, 'uid' => $uid, 'saas_appid' => $saas_appid,'state'=>State::YES['value']])->find();
        if (!$model) {
            return $this->fail('未找到渠道商信息');
        }
        $page=$request->post('page','pages/index/index');
        $qrcode_type=$request->post('qrcode_type','H5');
        $channels = getHpConfig('', $saas_appid, 'channels');
        $valid_time = 0;
        if (isset($channels['valid_time'])) {
            $valid_time = $channels['valid_time'];
        }
        switch($qrcode_type){
            case 'MP-WEIXIN':
                $applet = SettingsMgr::group($request->saas_appid, 'applet');
                if (empty($applet['applet_appid']) || empty($applet['applet_secret'])) {
                    return $this->fail('未开放小程序二维码');
                }
                $env_version = 'release';
                if (Env::get('APP_MODE') == 'dev') {
                    $env_version = 'trial';
                }
                $access_token = WechatHelper::getMPAccessToken($request->saas_appid);
                $url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token={$access_token}";
                $data = [
                    'scene' => "c={$channels_id}&t={$valid_time}",
                    'page' => $page,
                    'check_path' => false,
                    'width' => 1024,
                    'auto_color' => false,
                    'env_version' => $env_version,
                    'line_color' => ['r' => 0, 'g' => 0, 'b' => 0],
                ];
                $client = new Client();
                $response = $client->post($url, ['json' => $data]);
                $result = $response->getBody()->getContents();
                if (substr($result, 0, 1) == '{') {
                    $result = json_decode($result, true);
                    if (isset($result['errcode'])) {
                        return $this->fail("[{$result['errcode']}]" . $result['errmsg']);
                    }
                }
                $base64='data:image/png;base64,'.base64_encode($result);
                break;
            default:
                $domain = getHpConfig('domain', (int)$request->saas_appid, 'plugins_domains');
                $url=$domain . "/app/ycMassage/#/{$page}?appid={$request->saas_appid}&channels_id={$channels_id}&valid_time={$valid_time}";
                $builder = Builder::create()
                    ->writer(new PngWriter())
                    ->writerOptions([])
                    ->data($url)
                    ->encoding(new Encoding('UTF-8'))
                    ->errorCorrectionLevel(new ErrorCorrectionLevelHigh())
                    ->size(1024)
                    ->margin(10)
                    ->roundBlockSizeMode(new RoundBlockSizeModeMargin())
                    ->validateResult(false);
                $result = $builder->build();
                $base64 = $result->getDataUri();
                break;
        }
        return $this->successRes(['qrcode' => $base64]);
    }
}
